package com.dhcc.sdc.busi.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dhcc.cdc.sys.cache.config.CdcConfigCache;
import com.dhcc.cdc.sys.entity.ConfigurationEntity;
import com.dhcc.cdc.sys.service.IConfigurationService;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.DateUtil;
import com.dhcc.sdc.busi.dao.SdcBusiQcEliminateMapper;
import com.dhcc.sdc.busi.dao.SdcBusiQcTriggeredMapper;
import com.dhcc.sdc.busi.dao.SdcQcMapper;
import com.dhcc.sdc.busi.entity.*;
import com.dhcc.sdc.busi.service.IIPQCService;
import com.dhcc.sds.standard.dao.SdsStandRuleBaseMapper;
import com.dhcc.sds.standard.dao.SdsStandRuleCalMapper;
import com.dhcc.sds.standard.dao.SdsStandSourceFieldMapper;
import com.dhcc.sds.standard.dao.SdsStandSourceMapper;
import com.dhcc.sds.standard.service.IsdsStandRuleCalService;
import com.googlecode.aviator.AviatorEvaluator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("IPQCService")
public class IPQCServiceImpl implements IIPQCService {

    @Autowired
    private SdcQcMapper sdcQcMapper;
    @Autowired
    private SdcBusiQcTriggeredMapper sdcBusiQcTriggeredMapper;
    @Autowired
    private SdsStandSourceMapper sdsStandSourceMapper;
    @Autowired
    private SdsStandSourceFieldMapper sdsStandSourceFieldMapper;
    @Autowired
    private IConfigurationService configurationService;
    @Autowired
    private SdsStandRuleBaseMapper sdsStandRuleBaseMapper;
    @Autowired
    private SdsStandRuleCalMapper sdsStandRuleCalMapper;
    @Autowired
    IsdsStandRuleCalService isdsStandRuleCalService;
    @Autowired
    private SdcBusiQcEliminateMapper sdcBusiQcEliminateMapper;

    //小括号及其里面内容
    private static String p1 = "\\(.*?\\)";

    @Override
    public JSONArray QCInfo(Long episodeId, Long entityId) {
        JSONArray qcInfo = new JSONArray();
        HashMap params = new HashMap();
        params.put("qcentityId", entityId);
        params.put("episodeId", episodeId);
        params.put("isActive", 1);
        List<SdcQcEntity> qcItemList;
        // 获取VTE通用项目配置
        String vteQcModule = CdcConfigCache.me().getValueByKey("SDS", "VTEQcModule");
        if (vteQcModule.equals("Y")) {
            qcItemList = sdcQcMapper.list(params);
        } else {
            qcItemList = sdcQcMapper.selectConditionOfVte(params);
        }
        for (SdcQcEntity item : qcItemList) {
            params.put("qcId", item.getId());
            List<SdcBusiQcTriggeredEntity> sdcBusiQcTriggeredEntities = sdcBusiQcTriggeredMapper.list(params);
            int qcResult = sdcBusiQcTriggeredEntities.size();
            if (qcResult > 0 && CommonUtil.equals(item.getActiveOnce(), 1)) {
                JSONObject qcItemMap = new JSONObject();
                qcItemMap.put("QCDesc", item.getQcDesc());
                qcItemMap.put("QCMemo", item.getQcMemo());
                qcItemMap.put("QCSource", item.getSource());
                qcInfo.add(qcItemMap);
                continue;
            }
            // 解析质控项目表达式，且返回结果
//            boolean qcItemFlag = isdsStandRuleCalService.handleRuleExpressions(item.getQcExpression(),episodeId);
            Map<String,Object> res = (Map)isdsStandRuleCalService.handleRuleExpressions(item.getQcExpression(), episodeId,null);
            boolean qcItemFlag = (boolean)res.get("bool");
            if (qcItemFlag) {
                // 结果为true, 该质控项目触发，进行质控提醒，如果之前未触发保存到触发结果表
                //保存到触发结果表之前进行判断，质控项是否为医生手动纠正过,若是则不进行添加
                Wrapper<SdcBusiQcEliminateEntity> wrapper = new EntityWrapper<>();
                wrapper.eq("episode_id", episodeId).eq("qc_id",item.getId());
                List<SdcBusiQcEliminateEntity> list = sdcBusiQcEliminateMapper.selectList(wrapper);
                if (list == null || list.size() == 0) {
                    JSONObject qcItemMap = new JSONObject();
                    qcItemMap.put("QCDesc", item.getQcDesc());
                    qcItemMap.put("QCMemo", item.getQcMemo());
                    qcItemMap.put("QCSource", item.getSource());
                    qcInfo.add(qcItemMap);
                    if (qcResult == 0) {
                        SdcBusiQcTriggeredEntity sdcBusiQcTriggered = new SdcBusiQcTriggeredEntity();
                        sdcBusiQcTriggered.setEpisodeId(episodeId);
                        sdcBusiQcTriggered.setQcId(item.getId());
                        sdcBusiQcTriggered.setUpdateTime(new Date());
                        sdcBusiQcTriggeredMapper.insert(sdcBusiQcTriggered);
                    }
                }

            } else {
                // 如果为false未触发，且之前触发过，则删除触发结果表中数据
                if (qcResult > 0) {
                    sdcBusiQcTriggeredMapper.deleteById(sdcBusiQcTriggeredEntities.get(0).getId());
                }
            }
        }
        return qcInfo;
    }

    @Override
    public Integer deleteForbiddenQcTriggered(Long episodeId, Long entityId){
        Integer delete = 0;
        HashMap params = new HashMap();
        params.put("qcentityId", entityId);
        params.put("episodeId", episodeId);
        params.put("isActive", '0');
        List<SdcQcEntity> qcItemList;

        qcItemList = sdcQcMapper.list(params);

        if (qcItemList == null || qcItemList.size() == 0){
            return delete;
        }
        for (SdcQcEntity item : qcItemList) {
            params.put("qcId", item.getId());
            List<SdcBusiQcTriggeredEntity> sdcBusiQcTriggeredEntities = sdcBusiQcTriggeredMapper.list(params);
            int qcResult = sdcBusiQcTriggeredEntities.size();
            if (qcResult > 0) {
                for (SdcBusiQcTriggeredEntity entity : sdcBusiQcTriggeredEntities) {
                    Wrapper<SdcBusiQcTriggeredEntity> qcWpr = new EntityWrapper<>();
                    qcWpr.eq("episode_id",entity.getEpisodeId()).eq("qc_id",entity.getQcId());
                    sdcBusiQcTriggeredMapper.delete(qcWpr);
                    delete += 1;
                }
            }
        }
        return delete;
    }

    /**
     * 返回值改造
     *
     * @param bfVal
     * @param ruleType
     * @return
     */
    private String modelRuleValue(String bfVal, String ruleType) {
        String afVal = "";
        if (CommonUtil.isEmpty(bfVal)) {
            return afVal;
        }
        long divisor = 1;
        switch (ruleType) {
            case "Day":
                // 一天毫秒数
                divisor = 24 * 60 * 60 * 1000;
                afVal = String.valueOf(DateUtil.parse(bfVal).getTime() / divisor);
                break;
            case "Hour":
                // 1小时毫秒数
                divisor = 60 * 60 * 1000;
                afVal = String.valueOf(DateUtil.parse(bfVal).getTime() / divisor);
                break;
            case "Minute":
                // 一分钟毫秒数
                divisor = 60 * 1000;
                afVal = String.valueOf(DateUtil.parse(bfVal).getTime() / divisor);
                break;
            case "String":
                afVal = "\"" + bfVal + "\"";
                break;
            default:
                afVal = bfVal;
                break;
        }
        return afVal;
    }

    public static void main(String[] args) {

//        Object res = AviatorEvaluator.execute("1==2");
        Object res = AviatorEvaluator.execute("'有效'=='无效'");
        Object res2 = AviatorEvaluator.execute("\'无效\'=='无效'");
        Object res3 = AviatorEvaluator.execute("!\"\"");
        System.out.println(res);
        System.out.println(res2);
        System.out.println(res3);
    }
    @Override
    public List<String> QCBoxInfo(Long episodeId, Long entityId) {
        List<String> qcBoxItemList=sdcQcMapper.QCBoxInfo(episodeId,entityId);
        return qcBoxItemList;
    }
}
